package ws;

import com.mysql.jdbc.ResultSet;
import dbManagement.dbManager;
import dbManagement.notMyPatientException;
import hirondelle.date4j.DateTime;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import logManagement.Log4k;
import objects.userKind;
import objects.visitKind;
/**
 *
 * @author Lorenzo
 */
@Path("/sms")
public class SmsService {
    
    @GET
    @Path("visits/{id}{format:(/[^/]+?)?}")
    @Produces({MediaType.APPLICATION_XML})
    public ServiceHandler getVisits(@PathParam("id") String cellphone, @PathParam("format") String command) {
        ServiceHandler resList = null;
        dbManager db = new dbManager();
        if (!command.equals(""))
            command = command.substring(1);
        
        if (!db.existsThePatient(new Integer(db.getIDByCell(cellphone, userKind.PATIENT)))){
            ErrorHandler e = new ErrorHandler();
            e.setText("Il paziente richiesto non è stato trovato. Controllare i dati inseriti.");
            return e;
        } else {
        if (command.equalsIgnoreCase("VISITE") || command.isEmpty()){
            ResultSet res = db.getNotifiedVisitsByCell(cellphone);
            try {
                int i = 0;                     
                ArrayList<VisitHandler> list = new ArrayList();
                while(res.next()){
                    VisitHandler visit = new VisitHandler();
                    visit.setPatient_id(res.getInt("patient_id"));
                    visit.setPatient_name(res.getString("name") + " " + res.getString("surname"));
                    visit.setDoctor_id(res.getInt("doctor_id"));
                    ResultSet doc = db.getMyDoctorNameByCell(cellphone);
                    doc.next();
                    visit.setDoctor_name(doc.getString("name") + " " + doc.getString("surname"));
                    visit.setDate(res.getString("date"));
                    visit.setKind(res.getString("kind"));
                    visit.setReport(res.getString("report"));
                    visit.setReminder(res.getInt("reminder"));
                    list.add(visit);
                    i++;
                }
                if ( i == 0) 
                {
                    ErrorHandler e = new ErrorHandler();
                    e.setText("Nessun risultato trovato per i dati inseriti.");
                    return e; 
                }
                VisitList vlist = new VisitList();
                vlist.setVisitList(list);
                resList = vlist;
                
            } catch (SQLException ex) {
                Log4k.error(this.getClass().getName(), ex.getMessage());
                ErrorHandler e = new ErrorHandler();
                e.setText("Errore del server. Riprovare.");
                return e; 
            }
            
            
        } else if (command.equalsIgnoreCase("SCADENZE")){
            ResultSet res = db.getNextTwoYetUnscheduledVisits(cellphone);
            try {
                int i = 0;
                ArrayList<TermHandler> list = new ArrayList();
                while(res.next()){
                    TermHandler term = new TermHandler();
                    term.setDate(res.getString("date"));
                    term.setKind(res.getString("kind"));
                    term.setDescription(res.getString("description"));
                    ResultSet pat = db.getPatientByID(db.getIDByCell(cellphone, userKind.PATIENT), userKind.PATIENT);
                        pat.next();
                    term.setPatient_name(pat.getString("name") + " " + pat.getString("surname"));
                    list.add(term);
                    i++;
                }
                if ( i == 0) 
                {
                    ErrorHandler e = new ErrorHandler();
                    e.setText("Nessun risultato trovato per i dati inseriti.");
                    return e; 
                }
                TermList tlist = new TermList();
                tlist.setTermList(list);
                resList = tlist;
            } catch (SQLException ex) {
                Log4k.error(this.getClass().getName(), ex.getMessage());
                ErrorHandler e = new ErrorHandler();
                e.setText("Errore del server. Riprovare.");
                return e; 
            }
        } else {
           ErrorHandler e = new ErrorHandler();
            e.setText("Comando non valido. Controllare i dati inseriti.");
            return e;  
        }
        }
        db.releaseConnection();
        return resList;
    }
    
    
    @POST
    @Path("doctor")
    @Produces({MediaType.APPLICATION_XML})
    public ServiceHandler setVisit(@FormParam("doctor_id") String doctor, @FormParam("patient_id") String patient, @FormParam("description") String description) {
        try {
            DateTime date = addNewVisit(patient, new Integer(doctor), description);
            NewVisitHandler visit = new NewVisitHandler();
            visit.setPatient_id(patient);
            visit.setDoctor_id(doctor);
            visit.setDescription(description);
            visit.setDate(date.format("YYYY-MM-DD hh:mm:ss"));
            return visit;
            } catch (NullPointerException ex) {
                Log4k.error(this.getClass().getName(), ex.getMessage());
                ErrorHandler e = new ErrorHandler();
                e.setText("Errore del server. Riprovare.");
                return e;        
            } catch (notMyPatientException ex) {
                Log4k.error(this.getClass().getName(), ex.getMessage());
                ErrorHandler e = new ErrorHandler();
                e.setText("Il medico non ha i privilegi per gestire questo paziente. Controllare i dati inseriti.");
                return e;
            }
    }
    
    public DateTime addNewVisit(String patient_cell, int doctor_id, String report) throws notMyPatientException{
        //recupera data
        dbManager db = new dbManager();
        DateTime date = db.now();
        String dateStr = date.format("YYYY-MM-DD hh-mm-ss");
        
        
        int patient_id = new Integer (db.getIDByCell(patient_cell, userKind.PATIENT));
        int record_id = db.addVisit(patient_id, doctor_id, -1, date, visitKind.PATIENT_REQUEST, userKind.DOCTOR);
        db.doExamine(doctor_id, patient_id, record_id, report, userKind.DOCTOR);            
        
        db.releaseConnection();
        return date;
    }
}
